/**
 * Created by lijizhuang on 16/9/23.
 */
define(['jquery', 'underscore', 'backbone', 'text!modules/roomTypesMgr/pCalendarInfoView.html', 'modules/roomTypesMgr/modal/changeRoomTypePrice'],
    function ($, _, Backbone, PCalendarInfoViewTemplate, ChangeRoomTypePriceView) {
    var pCalendarInfoView = Backbone.View.extend({
        tagName: 'div',
        className:'pcInfo',
        template: _.template(PCalendarInfoViewTemplate),

        initialize: function () {
            _pCalendarInfoView = this;

            dragStart = -1;
            dragEnd = -1;
            isDragging = false;

            this.collection.on("change add remove", this.render, this);

            $('body').mouseup(this.onMouseUpBody);
        },

        events:{
            'mousedown .pcTable td':'onMouseDownCells',
            'mousemove .pcTable td':'onMouseMoveCells',
            //'mouseup .pcTable td': 'onMouseUpCells'
        },

        //得到表格行数
        tableRowCount: function () {
            return $('.pcTable tbody tr').length;
        },

        //得到表格列数
        tableColumnCount: function () {
            var colCount = 0;
            $('.pcTable tr:nth-child(1) td').each(function () {
                if ($(this).attr('colspan')) {
                    colCount += +$(this).attr('colspan');
                } else {
                    colCount++;
                }
            });

            return colCount;
        },

        //是否是右击
        isRightClick: function (e) {
            if (e.which) {
                return (e.which == 3);
            } else if (e.button) {
                return (e.button == 2);
            }
            return false;
        },

        onMouseDownCells: function (e) {
            if (this.isRightClick(e)) {
                return false;
            } else {
                var allCells = $(".pcTable td");
                if($(e.currentTarget).hasClass('canChangePrice'))
                {

                    dragEnd = dragStart = allCells.index($(e.currentTarget));
                    isDragging = true;

                    $(e.currentTarget).addClass('selected');

                    if (typeof e.preventDefault != 'undefined') {
                        e.preventDefault();
                    }

                    document.documentElement.onselectstart = function () {
                        return false;
                    };
                }
            }
        },

        onMouseMoveCells: function (e) {
            if (isDragging && $(e.currentTarget).hasClass('canChangePrice')) {
                var allCells = $(".pcTable tbody td");
                dragEnd = allCells.index($(e.currentTarget));
                this.selectRange();
            }
        },

        onMouseUpCells: function () {
            isDragging = false;

            this.selectRangeDone();
        },

        onMouseUpBody: function () {
            isDragging = false;
            _pCalendarInfoView.selectRangeDone();
        },

        selectRange: function () {
            var totalRowCount = this.tableRowCount();
            var totalColCount = this.tableColumnCount();

            //鼠标点击到鼠标松开的坐标
            var startCol = dragStart % totalColCount;
            var startRow = Math.floor(dragStart / totalColCount);
            var endCol = dragEnd % totalColCount;
            var endRow = Math.floor(dragEnd / totalColCount);

            $(".pcTable td").removeClass('selected');

            var fromRow = startRow, toRow = endRow, fromCol = startCol, toCol = endCol;

            //console.log('fromRow:' + fromRow + ' fromCol:' + fromCol + ' toRow:' + toRow + ' toCol:' + toCol);

            for (var r = fromRow; r <= toRow; ++r){
                for (var c = 0; c < totalColCount; ++c) {
                    if (r === fromRow && c < fromCol) continue;
                    if (r === toRow && c > toCol) continue;
                    $(".pcTable td:eq(" + (r * totalColCount + c) + ")").addClass('selected');
                }
            }
        },

        selectRangeDone: function () {

            if(dragStart === -1 && dragEnd ===  -1){
                return;
            }

            var totalRowCount = this.tableRowCount();
            var totalColCount = this.tableColumnCount();

            //console.log('totalRowCount:'+totalRowCount+' totalColCount:'+totalColCount);

            //鼠标点击到鼠标松开的坐标
            var startCol = dragStart % totalColCount;
            var startRow = Math.floor(dragStart / totalColCount);
            var endCol = dragEnd % totalColCount;
            var endRow = Math.floor(dragEnd / totalColCount);

            //弹层提示
            $(".pcTable td").removeClass('selected');

            var fromRow = startRow, toRow = endRow, fromCol = startCol, toCol = endCol;

            //console.log('fromRow:' + fromRow + ' fromCol:' + fromCol + ' toRow:' + toRow + ' toCol:' + toCol);

            if(fromRow === toRow && fromCol > toCol){
                //日期不支持从右往左选择
                return;
            }

            var selectPostions = [];
            var dateArray = []; //得到待修改价格的日期数组
            for (var r = fromRow; r <= toRow; ++r){
                for (var c = 0; c < totalColCount; ++c) {
                    if (r === fromRow && c < fromCol) continue;
                    if (r === toRow && c > toCol) continue;
                    $(".pcTable td:eq(" + (r * totalColCount + c) + ")").addClass('selected');
                    selectPostions.push(r + '-' + c);
                    dateArray.push($(".pcTable td:eq(" + (r * totalColCount + c) + ")").data('date')); //得到待修改价格的日期
                }
            }

            //console.log(selectPostions);

            if (selectPostions.length > 0) {
                var changeRoomTypePriceView = new ChangeRoomTypePriceView({collection: this.collection, dateArray:dateArray});
                if ($('body').find('#changeRoomTypePrice').length === 0) {
                    $('body').append(changeRoomTypePriceView.render().el);
                }
                else {
                    $('#changeRoomTypePrice').replaceWith(changeRoomTypePriceView.render().el);
                }

                $("#changeRoomTypePrice").modal({backdrop: 'static', keyboard: false});
            }

            dragEnd = dragStart = -1;
            $(".pcTable td.selected").removeClass('selected');
        },

        render: function () {
            this.$el.html(this.template({dailyPrices: this.collection}));
            return this;
        }
    });

    return pCalendarInfoView;
});